package cn.iocoder.yudao.module.wms.service.saleorder.listener;

import cn.iocoder.yudao.module.bpm.event.BpmProcessInstanceStatusEvent;
import cn.iocoder.yudao.module.bpm.event.BpmProcessInstanceStatusEventListener;
import cn.iocoder.yudao.module.wms.controller.admin.pomain.vo.PomainSaveReqVO;
import cn.iocoder.yudao.module.wms.controller.admin.saleorder.vo.SaleOrderSaveReqVO;
import cn.iocoder.yudao.module.wms.dal.dataobject.pomain.PomainDO;
import cn.iocoder.yudao.module.wms.dal.dataobject.pomain.PomainsDO;
import cn.iocoder.yudao.module.wms.dal.dataobject.saleorder.SaleDetailDO;
import cn.iocoder.yudao.module.wms.dal.dataobject.saleorder.SaleOrderDO;
import cn.iocoder.yudao.module.wms.enums.BpmnVariableConstants;
import cn.iocoder.yudao.module.wms.service.pomain.PomainService;
import cn.iocoder.yudao.module.wms.service.pomain.PomainServiceImpl;
import cn.iocoder.yudao.module.wms.service.saleorder.SaleOrderService;
import cn.iocoder.yudao.module.wms.service.saleorder.SaleOrderServiceImpl;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 销售订单监听器
 *
 * @author 芋道源码
 */
@Component
public class SaleOrderStatusListener extends BpmProcessInstanceStatusEventListener implements JavaDelegate {
    private static final Logger logger = LoggerFactory.getLogger(SaleOrderStatusListener.class);
    @Resource
    private SaleOrderService saleOrderService;

    @Override
    protected String getProcessDefinitionKey() {
        return SaleOrderServiceImpl.PROCESS_KEY;
    }

    @Override
    protected void onEvent(BpmProcessInstanceStatusEvent event) {
        saleOrderService.updateSaleOrderStatus(new SaleOrderSaveReqVO().setProcessInstanceId(event.getId()).setStatus(BpmnVariableConstants.BPM_APPROVED));
        if (event.getStatus().equals(BpmnVariableConstants.BPM_APPROVED)) {
            //通过流程ID获取主表信息
            SaleOrderDO saleOrderDO = saleOrderService.findByProcessInstanceId(event.getId());
            //获取子表信息
            List<SaleDetailDO> saleDetailDOList = saleOrderService.getSaleDetailListByPid(saleOrderDO.getId());
            //todo 对子表进行业务处理
            saleOrderService.businessProcessing(saleOrderDO, saleDetailDOList);
        }
    }

    @Override
    public void execute(DelegateExecution execution) {
        try {
            String reason = (String) execution.getVariable(BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_REASON);
        } catch (Exception e) {
            logger.error("Error in PomainStatusListener", e);
        }
    }
}
